<?php

/**
 * 应用程序的公共控制器基础类
 *
 * 可以在这个类中添加方法来完成应用程序控制器共享的功能。
 */
abstract class Controller_Abstract extends QController_Abstract
{
    /**
     * 控制器动作要渲染的数据
     *
     * @var array
     */
    protected $_view = array();

    /**
     * 控制器要使用的视图类
     *
     * @var string
     */
    protected $_view_class = 'QView_Render_PHP';

    /**
     * 控制器要使用的视图
     *
     * @var string
     */
    protected $_viewname = null;

    /**
     * 控制器所属的应用程序
     *
     * @var CommunityApp
     */
    protected $_app;

	protected $_site = array();
    /**
     * 构造函数
     */
    function __construct($app)
    {
        parent::__construct();
        $this->_app = $app;
    }

    /**
     * 执行指定的动作
     *
     * @return mixed
     */
    function execute($action_name, array $args = array())
    {
        $action_method = "action{$action_name}";

        // 执行指定的动作方法
        $this->_before_execute();
        

        #IFDEF DBEUG
        QLog::log('EXECUTE ACTION: '. get_class($this) . '::' . $action_method . '()', QLog::DEBUG);
        #ENDIF

        $response = call_user_func_array(array($this, $action_method), $args);
        $this->_after_execute($response);

        if (is_null($response) && is_array($this->_view))
        {
            // 如果动作没有返回值，并且 $this->view 不为 null，
            // 则假定动作要通过 $this->view 输出数据
            $config = array('view_dir' => $this->_getViewDir());
            $response = new $this->_view_class($config);
            $response->setViewname($this->_getViewName())->assign($this->_view);
            $this->_before_render($response);
        }
        elseif ($response instanceof $this->_view_class)
        {
            $response->assign($this->_view);
            $this->_before_render($response);
        }

        return $response;
    }

    /**
     * 指定的控制器动作未定义时调用
     *
     * @param string $action_name
     */
    function _on_action_not_defined($action_name)
    {
    }

    /**
     * 执行控制器动作之前调用
     */
    protected function _before_execute()
    {
		$servername = $_SERVER['SERVER_NAME'];
		if (substr($servername, 0, 4) == 'www.')
		{
			$domain = substr($servername, 4);
		}
		else
		{
			$domain = $servername;
		}
		$sitemodel = new Site();
		$site = $sitemodel->getSiteByDomain($domain);
		
		if ($site == false)
		{
			header(Util::HTTPStatus(500));
			exit;
		}
		$this->_site = $site;
		$this->_context->_domain = $site['domain'];
	
		//$_SESSION['PLAYED']=1;
		
	    if (Q::ini('appini/DEBUG') == 'true')
		{
			QDebug::enableFirePHP();
		}
		$socials = require_once APPLICATION_PATH . '/config/social.config.php';
 		$this->_view['fbsocials'] = $socials['facebook'][$domain];
 		$this->_view['twsocials'] = $socials['twitter'][$domain];

		if ($this->_app->currentUser())
		{
			$user = $this->_app->currentUser();		
			$usermodel = new User();
			$this->_view['user'] = $usermodel->getUserById($user['id']);
			$blueBarOfferModel = new BlueBarOffer();
			$this->_view['blueBarOffers'] = $blueBarOfferModel->getBlueBarOfferBySiteId($site['id']);
			
				
			$bannerOffersModel = new BannerOffers();
			$leftBannerOffer = $bannerOffersModel->getBannerOffers('left_banner', $site['id'], date('Y-m-d'), 0);
			if(empty($leftBannerOffer)){
				$leftBannerOffer = $bannerOffersModel->getBannerOffers('left_banner', $site['id'], null, 1);
			}
			if(!empty($leftBannerOffer)){
				$leftBannerOffer[] = array();
				shuffle($leftBannerOffer);
				if(!empty($leftBannerOffer[0])){
					$leftBannerOffer = $leftBannerOffer[0];
					$this->_view['leftBannerOfferPic'] = $leftBannerOffer['picture_url'];
					$this->_view['leftBannerOfferLink'] = url('default/bannerofferclick', array('bannerofferid' => $leftBannerOffer['id']));
					$this->_view['leftBannerId'] = $leftBannerOffer['id'];
				}
			}
			
			$rightBannerOffer = $bannerOffersModel->getBannerOffers('right_banner', $site['id'], date('Y-m-d'), 0);
			if(empty($rightBannerOffer)){
				$rightBannerOffer = $bannerOffersModel->getBannerOffers('right_banner', $site['id'], null, 1);
			}
			if(!empty($rightBannerOffer)){
				$rightBannerOffer[] = array();
				shuffle($rightBannerOffer);
				if(!empty($rightBannerOffer[0])){
					$rightBannerOffer = $rightBannerOffer[0];
					$this->_view['rightBannerOfferPic'] = $rightBannerOffer['picture_url'];
					$this->_view['rightBannerOfferLink'] = url('default/bannerofferclick', array('bannerofferid' => $rightBannerOffer['id']));
					$this->_view['rightBannerId'] = $rightBannerOffer['id'];
				}
			}
		} elseif (isset($_COOKIE[Q::ini('acl_cookie_key')])){
			list($email , $cookie) = unserialize($_COOKIE[Q::ini('acl_cookie_key')]);
			$usermodel = new User();
			$userUnsub = $usermodel->getUnsubByEmail($email);
			if($userUnsub == '0'){
				if(($user = $usermodel->validateCookie($email, $cookie, $site['id']))){
					$this->_view['user'] = $user;
					$this->_app->changeCurrentUser(array('id'=>$this->_view['user']['id']), 'MEMBER');
				}				
			}
		}
		
		$user = $this->_app->currentUser();
		if($user)
		{
			$usermodel = new User();
			$u = $usermodel->getUserById($user['id']);
			$tsNow = time();
			$tsCreated = $u['created'];
			$tsLastLogin = $u['last_visit'];
			if($tsNow <= TimeUtil::fiveDaysAfter($tsCreated) 
				&& $tsNow > TimeUtil::endOfDay($tsCreated)
				&& !TimeUtil::checkIsTheSameDay($tsLastLogin, $tsNow))
			{	
				$credit = 0;
				if ($this->_site['game'] == WHEEL)
				{
					$usermodel->offerUserCredits(1, $u['id']);
					$credit = 1;
				}
				else if ($this->_site['game'] == SLOT)
				{
					$usermodel->offerUserCredits(5, $u['id']);
					$credit = 5;
				}
				else if ($this->_site['game'] == POKER)
				{
					$usermodel->offerUserCredits(1, $u['id']);
					$credit = 1;
				}
				$this->_view['user'] = $usermodel->getUserById($user['id']);
				
				//TODO: recording free credits
				$record = new Record($u['id']);
				$record->addFreeCreditsRecording($credit);
			}
			$usermodel->updateLastVisit($u['id']);
		}
		$this->_view['site'] = $this->_site;
		if (empty($_SERVER['HTTPS']))
		{
// 			$this->_view['js_url'] = 'http://'.Q::ini('appini/IMAGE_SERVER_DOMAIN').'/js/';
// 			$this->_view['css_url'] = 'http://'.Q::ini('appini/IMAGE_SERVER_DOMAIN').'/'.$site['template'].'/css/';
// 			$this->_view['img_url'] = 'http://'.Q::ini('appini/IMAGE_SERVER_DOMAIN').'/'.$site['template'].'/img/';
			
			$this->_view['js_url'] = "http://{$site['domain']}/{$site['name']}/js/";
			$this->_view['css_url'] = "http://{$site['domain']}/{$site['name']}/css/";
			$this->_view['img_url'] = "http://{$site['domain']}/{$site['name']}/img/";

//			$this->_view['js_url'] = "http://image.cgb.s3.amazonaws.com/js/";
//			$this->_view['css_url'] = "http://image.cgb.s3.amazonaws.com/" . $site['name'] . "/css/";
//			$this->_view['img_url'] = "http://image.cgb.s3.amazonaws.com/" . $site['name'] . "/img/";
			
			//$this->_view['js_url'] = 'http://www.gameco.frontend/mommymoolah.com/js/';
			//$this->_view['css_url'] = 'http://www.gameco.frontend/mommymoolah.com/css/';
			//$this->_view['img_url'] = 'http://www.gameco.frontend/mommymoolah.com/img/';
			
			$this->_view['flash_url'] = 'http://'.Q::ini('appini/IMAGE_SERVER_DOMAIN').'/flash/';
		}
		else
		{
			$this->_view['js_url'] = 'https://'.Q::ini('appini/IMAGE_SERVER_DOMAIN').'/js/';
			$this->_view['css_url'] = 'https://'.Q::ini('appini/IMAGE_SERVER_DOMAIN').'/'.$site['template'].'/css/';
			$this->_view['img_url'] = 'https://'.Q::ini('appini/IMAGE_SERVER_DOMAIN').'/'.$site['template'].'/img/';
			$this->_view['flash_url'] = 'https://'.Q::ini('appini/IMAGE_SERVER_DOMAIN').'/flash/';
		}
		$this->_view['flash_version'] = '20111027';
		$this->_view['game'] = $site['game'];
		$user = $this->_app->currentUser();
		if (empty($user))
		{
			$pixelmodel = new Pixel();
			$pixels = $pixelmodel->getPixels($this->_site['id'], 'not_login');
			if (!empty($_SESSION['pixel']) && !empty($pixels))
			{
				$_SESSION['pixels'] = array_merge($_SESSION['pixels'], $pixels);
			}
			else if (!empty($pixels))
			{
				$_SESSION['pixels'] = $pixels;
			}
		}
		if (isset($_SESSION['pixels']) && $this->_context->controller_name != 'game'
			&& !($this->_context->controller_name == 'user' && $this->_context->action_name == 'adflow'))
		{
			$this->_view['pixels'] = $_SESSION['pixels'];
			unset($_SESSION['pixels']);
		}
		
		if(isset($this->_context->emailId) && isset($this->_context->pos)){
			$emailId = $this->_context->emailId;
			$pos = $this->_context->pos;	
			$emailModel = new Email();
			$emailModel->updatePos($emailId, $pos);	
		}
    }

    /**
     * 执行控制器动作之后调用
     *
     * @param mixed $response
     */
    protected function _after_execute(& $response)
    {
    }

    /**
     * 渲染之前调用
     *
     * @param QView_Render_PHP
     */
    protected function _before_render($response)
    {
    }

    /**
     * 准备视图目录
     *
     * @return array
     */
    protected function _getViewDir()
    {
        if ($this->_context->module_name)
        {
            $dir = Q::ini('app_config/MODULE_DIR') . "/{$this->_context->module_name}/view";
        }
        else
        {
            $dir = Q::ini('app_config/APP_DIR') . '/view';
        }

        if ($this->_context->namespace)
        {
            $dir .= "/{$this->_context->namespace}";
        }
        return $dir;
    }

    /**
     * 确定要使用的视图
     *
     * @return string
     */
    protected function _getViewName()
    {
        if ($this->_viewname === false)
        {
            return false;
        }
        $viewname = empty($this->_viewname) ? $this->_context->action_name : $this->_viewname;
        return strtolower("{$this->_context->controller_name}/{$viewname}");
    }

    /**
     * 显示一个提示页面，然后重定向浏览器到新地址
     *
     * @param string $caption
     * @param string $message
     * @param string $url
     * @param int $delay
     * @param string $script
     *
     * @return QView_Render_PHP
     */
    protected function _redirectMessage($template_name, $caption, $message, $url, $delay = 5, $script = '')
    {
        $config['view_dir'] = Q::ini('templates_root').'/'.$template_name;
        $response = new $this->_view_class($config);
        $response->setViewname('redirect_message');
        $response->assign(array(
            'message_caption'   => $caption,
            'message_body'      => $message,
            'redirect_url'      => $url,
            'redirect_delay'    => $delay,
            'hidden_script'     => $script,
        ));

        return $response;
    }
    
	protected function display($template_name, $viewname = '')
	{
		if(empty($viewname)){
			$viewname = empty($this->_viewname) ? $this->_context->action_name : $this->_viewname;
			$viewname = strtolower("{$this->_context->controller_name}/{$viewname}");
		}else
			$viewname = strtolower($viewname);
		$config = array();
		$config['view_dir'] = Q::ini('templates_root').'/'.$template_name;
		$response = new $this->_view_class($config);		
	
		$sitemodel = new Site();
		$acitivitymodel = new Activity();////////////
		$this->_site['winners'] = $sitemodel->getWinners($this->_site['id']);
		$this->_site['activities'] = $acitivitymodel->getRecentActivities($this->_site['id']);
		$this->_view['site'] = $this->_site;
		
		$response->setViewname($viewname)->assign($this->_view);
		return $response;
	}
}

